package com.ctgu.admin.system.controller;

import cn.hutool.core.util.StrUtil;
import com.ctgu.admin.Utils.PlainHtmlUtil;
import com.ctgu.admin.system.domain.Article;
import com.ctgu.admin.system.domain.Information;
import com.ctgu.admin.system.service.ArticleService;
import com.ctgu.admin.system.service.InformationService;
import com.ctgu.admin.system.validator.ArticleValid;
import com.ctgu.common.enums.StatusEnum;
import com.ctgu.common.exception.ResultException;
import com.ctgu.common.utils.EntityBeanUtil;
import com.ctgu.common.utils.EnumUtils;
import com.ctgu.common.utils.ResultVoUtil;
import com.ctgu.common.utils.StatusUtil;
import com.ctgu.common.vo.ResultVo;
import com.ctgu.component.fileUpload.FileUpload;
import com.ctgu.component.fileUpload.enums.UploadResultEnum;
import com.ctgu.component.shiro.ShiroUtil;
import com.ctgu.devtools.generate.utils.jAngel.utils.StringUtil;
import com.ctgu.modules.system.domain.Dict;
import com.ctgu.modules.system.domain.Upload;
import com.ctgu.modules.system.domain.User;
import com.ctgu.modules.system.service.DictService;
import com.ctgu.modules.system.service.UploadService;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller
@RequestMapping("/submission")
public class SubmissionController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private InformationService informationService;

    @Autowired
    private UploadController uploadController;
    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    public String toAdd() {
        return "/system/article/add";
    }
    /**
     * 用户投稿
     * @param mainPicture 用于接收前端Ajax传来的图片文件
     */
    @PostMapping("/article")
    @ResponseBody
    public Map<String,Object> submission(Article article, @RequestParam("mainImage") MultipartFile mainPicture,
                             Model model) {
        // 复制保留无需修改的数据
       // Article article = new Article();
//        article.setTitle(title);
//        article.setContent(content);
//        article.setArticleClass(articleClass);

        if (article.getId() != null) {
            Article beArticle = articleService.getById(article.getId());
            EntityBeanUtil.copyProperties(beArticle, article);
        }

        String content = PlainHtmlUtil.splitAndFilterString(article.getContent());
        String title = article.getTitle();

        List<String> list1 = SensitiveWordHelper.findAll(title);
        List<String> list2 = SensitiveWordHelper.findAll(content);
        List<String> list = new ArrayList<>();
        String example;
        // 排除一个字的敏感词
        for(String str : list1){
            if(str.length() > 1){
                list.add(str);
            }
        }
       for(String str:list2){
           if(str.length() > 1){
               list.add(str);
           }
       }
       Map<String, Object>result = new HashMap<String,Object> ();
       // 存在敏感词
       if(list.size() != 0){
           String filterString = String.join(",", list);
           result.put("filterString",filterString);
           result.put("submitResult",false);
           model.addAttribute("example",list.get(0));
//           System.out.println(list);
           return result;
       }

        //用户投稿时给小编发送一个消息
        User user = ShiroUtil.getSubject();
        Information information = new Information();
        Map map = EnumUtils.getArticleClassMap();
        String str;
        if(article.getArticleClass() == null)
            str = user.getNickname() + "投稿了一篇文章,请及时审查";
        else
            str = user.getNickname() + "投稿了一篇" + map.get(article.getArticleClass()) + ",请及时审查";
        information.setContent(str);
        information.setTitle("投稿通知");
        information.setUserID(5L);
        information.setCreateDate(new Date());
        information.setUpdateDate(new Date());
        information.setStatus((byte)0);

        informationService.save(information);
        // 保存数据
        if(article.getArticleClass() == null)
            article.setArticleClass((byte)5); //其他


        // 上传帖子主要图片，并获得结果
        ResultVo imageResult = uploadController.uploadPicture(mainPicture);
        if(imageResult.getMsg().equals("成功"))
            article.setMainPicture(((Upload) imageResult.getData()).getPath());

        articleService.save(article);
        model.addAttribute("operation","投稿");
        model.addAttribute("msg","投稿成功");
        result.put("submitResult",true);
        return result;
    }

    /**
     * 修改某一篇投稿
     */
    @PostMapping("/editSubmission")
    public String editSubmission(Article article, @RequestParam("mainImage") MultipartFile mainPicture,
                             Model model) {
        Article originArticle = articleService.getById(article.getId());
        // 上传帖子主要图片，并获得结果
        if(mainPicture!=null){
            ResultVo imageResult = uploadController.uploadPicture(mainPicture);
            if(imageResult.getMsg().equals("成功"))
                article.setMainPicture(((Upload) imageResult.getData()).getPath());
            if(article.getMainPicture()!=null)
                originArticle.setMainPicture( article.getMainPicture() );
        }

        User user = ShiroUtil.getSubject();
        // 保存数据
        originArticle.setContent(article.getContent());
        originArticle.setArticleClass(article.getArticleClass());
        originArticle.setTitle(article.getTitle());
        originArticle.setUpdateBy(user);



//        System.out.println("准备修改"+originArticle.toString());
        articleService.save(originArticle);
        model.addAttribute("user",user);

        List<Article> articleList = articleService.getUserArticles(user);
        model.addAttribute("articleList", articleList);

        return "redirect:/userPage/myArticle";
    }
    /**
     * 跳转到投稿
     */
    @GetMapping("/index")
    public String toSubmission(Model model){
        User user = ShiroUtil.getSubject();
        model.addAttribute("user",user);
        return "/submission/index";
    }
    /**
     * 跳转到管理员编辑页面
     */
    @GetMapping("/edit/{id}")
    public String toEdit(@PathVariable("id") Article article, Model model) {
        model.addAttribute("article", article);
        return "/system/article/add";
    }


    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @ResponseBody
    public ResultVo save(@Validated ArticleValid valid, Article article) {
        // 复制保留无需修改的数据
        if (article.getId() != null) {
            Article beArticle = articleService.getById(article.getId());
            EntityBeanUtil.copyProperties(beArticle, article);
        }

        // 保存数据
        articleService.save(article);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    public String toDetail(@PathVariable("id") Article article, Model model) {
        model.addAttribute("article",article);
        return "/system/article/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (articleService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }

}